<template>
  <el-card class="workspace-conterner">
    <template #header>
      <div class="workspace-query" :style="{ height: '90px' }">
        <div class="workspace-query-title">
          <span class="normal-title">工作空间</span
          ><span class="title-description">管理所有工作空间</span>
        </div>
        <el-form class="workspace-query-form" :model="workspaceQueryFormData" :inline="true">
          <el-form-item label="名称 :">
            <el-input v-model="workspaceQueryFormData.name" placeholder="请输入..." />
          </el-form-item>
          <el-form-item style="margin-left: auto">
            <el-button @click="reset">重置</el-button>
            <el-button @click="startQuery">查询</el-button>
            <el-button type="primary" size="small" @click="addWorkspace">新增</el-button>
          </el-form-item>
        </el-form>
      </div>
    </template>
    <div class="card-body-conterner">
      <el-table
        ref="workspaceTableRef"
        :data="paginatedTableData"
        style="width: 100%"
        class="workspace-table"
        header-cell-class-name="workspace-table-header-cell"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="名称" prop="name" width="200"> </el-table-column>
        <el-table-column label="URI" prop="nsUri"> </el-table-column>
        <el-table-column label="创建时间">
          <template #default="scope">
            <div style="display: flex; align-items: center">
              <span style="margin-left: 10px">{{
                scope?.row?.dateCreated ? dateFormat(scope.row.dateCreated) : ''
              }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="设为默认">
          <template #default="scope">
            <img
              v-if="scope?.row?.default"
              style=""
              src="@/assets/images/default.png"
              fit="contain"
            />
            <span
              v-else
              style="
                font-size: 12px;
                font-weight: 400;
                line-height: 12px;
                color: #2a78ff;
                cursor: pointer;
              "
              @click="setDefaultWorkspace(scope.row)"
              >设为默认</span
            >
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-tooltip class="box-item" effect="dark" content="编辑" placement="bottom">
              <img
                style="margin-right: 12px; cursor: pointer"
                src="@/assets/images/edit.png"
                fit="contain"
                @click="handleEdit(scope.row)"
              />
            </el-tooltip>
            <el-tooltip class="box-item" effect="dark" content="删除" placement="bottom">
              <img
                style="cursor: pointer"
                src="@/assets/images/delete.png"
                fit="contain"
                @click="handleDelete(scope.row)"
              />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-if="totalOrignTableData > 10"
        v-model:current-page="workspaceQueryFormData.pageNum"
        v-model:page-size="workspaceQueryFormData.pageSize"
        class="workspace-pagination"
        :page-sizes="[10, 20, 50, 100]"
        :background="true"
        layout="prev, pager, next, total, sizes"
        :total="totalOrignTableData"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <addOrUpdate ref="addOrUpdateRef" @update-workspace="updateWorkspace"></addOrUpdate>
  </el-card>
</template>

<script setup lang="ts" name="authButton">
import { ElMessage, ElMessageBox, ElTable } from 'element-plus'
import useWorkspaceModal from '@/composables/useWorkspace'
import { dateFormat } from '@/utils/util'
import addOrUpdate from './addOrUpdate.vue'
import { computed, onMounted, reactive, ref } from 'vue'
import type { IWorkspace } from 'geoserver-helper/interface'
import { restHelperInstance } from '@/composables/useGeoHelper'

const workspaceTableRef = ref<InstanceType<typeof ElTable>>()
const workspaceModal = useWorkspaceModal()
interface workspaceFormDialogExpose {
  openDialog: (opentionTypeParam?: string) => void
  setOrignWorkspace: (orignWorkspaceParam: IWorkspace.WorkspaceOverview) => void
}
const addOrUpdateRef = ref<workspaceFormDialogExpose | undefined>()
const workspaceQueryFormData = reactive({
  name: '',
  pageNum: 1,
  pageSize: 10,
})
// 选中的工作空间
const workspaceSelection = ref<IWorkspace.WorkspaceOverview[]>([])
const handleEdit = (row: IWorkspace.WorkspaceOverview) => {
  editWorkspace(row)
}
/**
 * @description: 表格选中事件
 * @param {*} val
 * @return {*}
 */
const handleSelectionChange = (val: IWorkspace.WorkspaceOverview[]) => {
  workspaceSelection.value = val
}
interface IWorkspaceTableInfo extends IWorkspace.WorkspaceOverview {
  dateCreated?: string
  isolated?: false
  nsUri?: string
  default?: boolean
}

const orignTableData = ref<IWorkspaceTableInfo[]>([])

//分页数据
const paginatedTableData = computed(() => {
  return orignTableData.value.slice(
    (workspaceQueryFormData.pageNum - 1) * workspaceQueryFormData.pageSize,
    workspaceQueryFormData.pageNum * workspaceQueryFormData.pageSize,
  )
})
// 数据总数
const totalOrignTableData = ref(0)

const initWorkspaceInfo = () => {
  orignTableData.value.forEach((singleWorkspaceItem) => {
    restHelperInstance.getWorkspaceInfoApi(singleWorkspaceItem.name).then((infoRes) => {
      if (typeof infoRes != 'string') {
        singleWorkspaceItem.dateCreated = infoRes.workspace.dateCreated
        singleWorkspaceItem.isolated = infoRes.workspace.isolated
      }
      // singleWorkspaceItem.nsUri = infoRes.workspace.nsUri
    })
    restHelperInstance.getNamespacesInfoApi(singleWorkspaceItem.name).then((namespaceInfo) => {
      singleWorkspaceItem.nsUri = namespaceInfo.namespace.uri
    })
    if (workspaceModal.defaultWorkspace.value.name == singleWorkspaceItem.name) {
      singleWorkspaceItem.default = true
    } else {
      singleWorkspaceItem.default = false
    }
  })
}

/**
 * @description: 重置
 * @return {*}
 */
const reset = () => {
  workspaceQueryFormData.name = ''
  workspaceQueryFormData.pageNum = 1
  workspaceQueryFormData.pageSize = 10
}

/**
 * @description: 查询工作空间
 * @return {*}
 */
const startQuery = () => {
  totalOrignTableData.value = 0
  orignTableData.value = []
  workspaceModal.getDefaultWorkspace().then(() => {
    workspaceModal.getWorkspaceList().then((res) => {
      res.forEach((singleWorkspace) => {
        if (workspaceQueryFormData.name) {
          if (singleWorkspace.name.includes(workspaceQueryFormData.name)) {
            totalOrignTableData.value += 1
            orignTableData.value.push(singleWorkspace)
          }
        } else {
          totalOrignTableData.value += 1
          orignTableData.value.push(singleWorkspace)
        }
      })
      initWorkspaceInfo()
    })
  })
}

/**
 * @description: 更新工作空间
 * @return {*}
 */
const updateWorkspace = () => {
  Promise.all([
    workspaceModal.getWorkspaceList(true),
    workspaceModal.getDefaultWorkspace(true),
  ]).then(() => {
    startQuery()
  })
}
const addWorkspace = () => {
  if (addOrUpdateRef.value) {
    addOrUpdateRef.value.openDialog('新增')
  }
}
const editWorkspace = (readyToUpdateWorkspace: IWorkspace.WorkspaceOverview) => {
  if (addOrUpdateRef.value) {
    addOrUpdateRef.value.setOrignWorkspace(readyToUpdateWorkspace)
    addOrUpdateRef.value.openDialog('编辑')
  }
}
const handleDelete = (row: IWorkspace.WorkspaceOverview) => {
  ElMessageBox.confirm('删除会连带着删除附属的图层，确认删除该工作空间么?', '', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      restHelperInstance.deleteWorkspaceApi(row.name).then((res) => {
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
        updateWorkspace()
      })
    })
    .catch(() => {})
}

/**
 * @description: 设置默认的工作空间
 * @return {*}
 */
const setDefaultWorkspace = (row: IWorkspaceTableInfo) => {
  ElMessageBox.confirm('确认设置该工作空间为默认工作空间么?', '', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      const operationForm: IWorkspace.WorkspaceOperationForm = {
        name: row.name,
      }
      restHelperInstance.updateWorkspaceApi('default', operationForm).then(() => {
        ElMessage({
          type: 'success',
          message: '设置成功',
        })
        updateWorkspace()
      })
    })
    .catch(() => {})
}

/**
 * @description: 每页显示条数改变事件
 * @return {*}
 */
const handleSizeChange = () => {
  startQuery()
}
/**
 * @description: 当前页改变事件
 * @return {*}
 */
const handleCurrentChange = () => {
  startQuery()
}
onMounted(() => {
  startQuery()
})
</script>

<style scoped lang="scss">
@import './index';
</style>
